<template>
  <Dialog v-model="dialogVisible" title="督导检查模板" width="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="formData.templateName" placeholder="请输入模板名称" />
      </el-form-item>
      
      <el-form-item label="适用范围" prop="applicableScope">
        <el-select
          v-model="formData.applicableScope"
          placeholder="请选择适用范围"
          style="width: 100%"
        >
          <el-option label="理论考试" value="理论考试" />
          <el-option label="实操考核" value="实操考核" />
          <el-option label="综合评审" value="综合评审" />
          <el-option label="全部环节" value="全部环节" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="检查项目">
        <div class="check-items">
          <div
            v-for="(item, index) in formData.checkItems"
            :key="index"
            class="check-item"
          >
            <el-input
              v-model="item.itemName"
              placeholder="检查项目名称"
              style="width: 200px; margin-right: 10px;"
            />
            <el-input
              v-model="item.checkPoints"
              placeholder="检查要点"
              style="width: 300px; margin-right: 10px;"
            />
            <el-button
              type="danger"
              size="small"
              @click="removeCheckItem(index)"
              :disabled="formData.checkItems.length <= 1"
            >
              删除
            </el-button>
          </div>
          <el-button type="primary" size="small" @click="addCheckItem">
            添加检查项目
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="评分标准">
        <el-input
          v-model="formData.scoringCriteria"
          type="textarea"
          :rows="4"
          placeholder="请输入评分标准"
        />
      </el-form-item>
      
      <el-form-item label="模板说明">
        <el-input
          v-model="formData.templateDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入模板说明"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'SupervisionTemplate' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

const formData = reactive({
  id: undefined,
  templateName: '',
  applicableScope: '',
  checkItems: [
    { itemName: '', checkPoints: '' }
  ],
  scoringCriteria: '',
  templateDescription: ''
})

const formRules = reactive({
  templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  applicableScope: [{ required: true, message: '请选择适用范围', trigger: 'change' }]
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  resetForm()
  
  if (type === 'update' && id) {
    formLoading.value = true
    try {
      // TODO: 调用获取模板详情的API
      // const data = await getSupervisionTemplate(id)
      // Object.assign(formData, data)
    } catch (error) {
      console.error('获取模板详情失败:', error)
    } finally {
      formLoading.value = false
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.id = undefined
  formData.templateName = ''
  formData.applicableScope = ''
  formData.checkItems = [{ itemName: '', checkPoints: '' }]
  formData.scoringCriteria = ''
  formData.templateDescription = ''
  formRef.value?.resetFields()
}

/** 添加检查项目 */
const addCheckItem = () => {
  formData.checkItems.push({ itemName: '', checkPoints: '' })
}

/** 删除检查项目 */
const removeCheckItem = (index: number) => {
  if (formData.checkItems.length > 1) {
    formData.checkItems.splice(index, 1)
  }
}

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  // 验证检查项目
  const hasEmptyItem = formData.checkItems.some(item => !item.itemName || !item.checkPoints)
  if (hasEmptyItem) {
    ElMessage.error('请完善所有检查项目信息')
    return
  }
  
  try {
    formLoading.value = true
    
    if (formData.id) {
      // TODO: 调用更新模板的API
      // await updateSupervisionTemplate(formData)
      ElMessage.success('模板更新成功')
    } else {
      // TODO: 调用创建模板的API
      // await createSupervisionTemplate(formData)
      ElMessage.success('模板创建成功')
    }
    
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存模板失败')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.check-items {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.check-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.check-item:last-of-type {
  margin-bottom: 15px;
}
</style>
